const debounce = (func, wait, immediate) => {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function formatDate(dateStr) {
  dateStr = dateStr.replace(/-/g, "/")
  const date = new Date(dateStr);
  const now = new Date();
  const y = date.getFullYear(),
    m = date.getMonth(),
    d = date.getDate()
  const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
  if (y == now.getFullYear() && m == now.getMonth() && d == now.getDate()) {
    return `${supplement(date.getHours())}:${supplement(date.getMinutes())}`;
  } else if (y == yesterday.getFullYear() && m == yesterday.getMonth() && d == yesterday.getDate()) {
    return "昨天"
  } else if (y == now.getFullYear()) {
    return `${supplement(m + 1)}/${supplement(d)}`;
  } else {
    return `${y}/${supplement(m + 1)}/${supplement(d)}`;
  }
}

function supplement(value, len = 2, symbol = "0") {
  value = value + ""
  return value.padStart(len, symbol)
}

const loadingShow = function () {
  getCurrentPages()[0].selectComponent("#loading").show()
}
const loadingHide = function () {
  getCurrentPages()[0].selectComponent("#loading").hide()
}


module.exports = {
  formatTime,
  debounce,
  formatDate,
  loadingShow,
  loadingHide,
}